package com.gitee.sparta.examples.broadcast;

import com.alibaba.fastjson2.JSON;
import com.gitee.sparta.annotation.BroadcastListener;
import com.gitee.sparta.api.SpartaTemplate;
import com.gitee.sparta.examples.TopicConstant;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.Random;

/**
 * <p>
 *      广播消费者 1
 * </p>
 *
 * @author zyred
 * @since v 0.0.2
 */
@Slf4j
@RestController
@RequestMapping("/broadcast")
public class SpartaBroadcastListener {

    @SuppressWarnings("all")
    @Autowired private SpartaTemplate<Object> spartaTemplate;

    @BroadcastListener(channels = {TopicConstant.BROADCAST, TopicConstant.BROADCAST_A})
    public void broadcastListener1 (BroadcastEntity entity) {
        log.info("[消费者1] :{}", JSON.toJSONString(entity));
    }

    @BroadcastListener(channels = {TopicConstant.BROADCAST, TopicConstant.BROADCAST_B})
    public void broadcastListener2 (BroadcastEntity entity) {
        log.info("[消费者2] :{}", JSON.toJSONString(entity));
    }


    /**
     * 添加广播消息到队列中
     * <a href="http://localhost:9605/broadcast/put?channel=BROADCAST_TOPIC&scope=2000">...</a>
     *
     * @param channel       广播通道可选：BROADCAST、BROADCAST_A、BROADCAST_B
     * @param scope         随机数范围，随机延迟时间
     */
    @GetMapping("/put")
    public void put (String channel, int scope) {
        Random random = new Random();
        int next = random.nextInt(scope);
        BroadcastEntity entity = new BroadcastEntity();
        entity.setUserId(String.valueOf(next));
        this.spartaTemplate.writeBroadcast(channel, entity, next);
    }
}
